<?php
namespace yan\csp;
/**
 * head add
 * <?=\yan\csp\ContentSecurityPolicy::widget([
    'contents'=>[
      'default-src' => ['self', '*.fortress-go-green.com', '*.googletagmanager.com','*.google-analytics.com'],
      'style-src' => ['self', 'unsafe-inline', '*.fortress-go-green.com', '*.googletagmanager.com','*.google-analytics.com'],
      'script-src' => ['self', 'unsafe-eval', 'unsafe-inline', '*.fortress-go-green.com', '*.googletagmanager.com','*.google-analytics.com','*.google.com'],
      'connect-src' => ['self', 'unsafe-inline', 'unsafe-eval', 'data:', 'blob:', '*.fortress-go-green.com', '*.googletagmanager.com','*.google-analytics.com'],
      'img-src' => ['self', 'unsafe-inline', 'unsafe-eval', 'data:', '*.fortress-go-green.com', '*.googletagmanager.com','*.google-analytics.com'],
      'font-src' => ['self', 'unsafe-inline', 'unsafe-eval', 'data:', '*.fortress-go-green.com', '*.googletagmanager.com','*.google-analytics.com'],
    ],
  ]);?>
 * */
class ContentSecurityPolicy extends \yii\base\Widget{
	/**
	 * default-src style-src connect-src img-src font-src
	 * */
	public $contents = [];
	public function run(){
		return $this->renderMeta();
	}
	public function add($src, $params){
		$this->contents[$src] = $params;
	}
	public function renderMeta(){
		$contents = [];
		foreach ($this->contents as $key => $val) {
			$contents[] = $key . ' ' . $this->formatSource($val);
		}
		$content = implode(';', $contents);
		echo '<meta http-equiv="Content-Security-Policy" content="'.$content.'" />';
	}
	public function formatSource($sources){
		$value = [];
		if(is_array($sources)){
			foreach($sources as $source){
				if($this->isNeed($source)){
					$value[] = "'{$source}'";
				}else{
					$value[] = "{$source}";
				}
			}
		}else{
			if($this->isNeed($sources)){
				$value[] = "'{$sources}'";
			}else{
				$value[] = "{$sources}";
			}
		}
		return implode(' ', $value);
	}
	public function isNeed($str){
		$need = ['self', 'unsafe-inline', 'unsafe-eval', 'none'];
		if(in_array($str, $need)){
			return true;
		}
		if( strpos($str, 'nonce-')!==false ){
			return true;
		}
		
		return false;
	}
	public function isValidDomain($domain) {
	    // 正则表达式匹配域名
	    $pattern = "/^([a-z0-9]([a-z0-9\-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9\-]{0,61}[a-z0-9]$/i";
	    return preg_match($pattern, $domain);
	}
	public function isValidIP($ip) {
	    return filter_var($ip, FILTER_VALIDATE_IP) !== false;
	}
}